import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *




def On_InputPage_InputLogistics(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Logistics_Template_Name:str="系统模板-商家默认模板"):
    try:
        xpath_value = f"//label[./span[text()='使用物流配送'] and .//input]//input[@type='checkbox']"
        element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        # 勾选使用物流配送
        if element.get_attribute("checked") != "true":
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
                try:
                    wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
                except TimeoutException:
                    print(f"提示 : 没有检测到 [运费模板] 元素!")


        # 选择运费模板
        try:
            xpath_value = f"//div[contains(@class,'template') and .//*[text()='运费模板'] and .//input[@role='combobox']]//input[@role='combobox']"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
            
            # 打开模板选项框
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            except TimeoutException:
                print(f"提示 : 没有检测到 [{Logistics_Template_Name}] 运费模板的元素选项!")
                
            # 选择 [运费模板]
            xpath_value = f"//ul/li/div/span[text()='{Logistics_Template_Name}']"
            element = wait.until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
            
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)

        except TimeoutException:
            print(f"提示 : 没有检测到 [运费模板] 元素!")
            return


    except TimeoutException:
        print(f"提示 : 没有找到 [使用物流配送] 的元素选项!")     